package com.atguigu.spzx.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.utils.ThreadLocalUtil;
import com.atguigu.spzx.common.exp.GuiguException;
import com.atguigu.spzx.manager.controller.SysUserVo;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;




    @Override
    //登录接口
    public LoginVo login(LoginDto loginDto) {

        //0.校验验证码

        this.checkCapchaCode(loginDto);

        //1.非空校验
        String userName= loginDto.getUserName();
        String password = loginDto.getPassword();
        //对前端传来的两个数据进行 非空校验
        if(StringUtils.isEmpty(userName)||StringUtils.isEmpty(password)){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        //从数据库获取信息
        // 2.根据用户名查询当前的用户 SysUser里面包含了密码
        //查询用户信息用的密码
      SysUser sysuser =  sysUserMapper.findByUsername(userName);
        //3.不存在抛出异常
      if(sysuser==null){
          throw new GuiguException(ResultCodeEnum.LOGIN_noexist);
      }
      //4.用户存在 对用户输入的密码进行验证
        String passwordFromDb = sysuser.getPassword();
        if(!passwordFromDb.equals(DigestUtils.md5Hex(password))){
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
      //5.检查用户的状态是否禁用
      if(sysuser.getStatus()==0){
          throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
      }

      //6.密码校验通过 状态为1 将用户信息 暂存为redis k-v

        // k = user:login:token token是uuid去掉-的字符串
        // v = 当前用户信息的JSON字符串

        String token = UUID.randomUUID().toString().replaceAll("-","");

        //自定义的一个key
        String key = "user:login:" + token;

        //用户对象转换为json
        String value = JSON.toJSONString(sysuser);

        redisTemplate.opsForValue().set(key,value,30, TimeUnit.MINUTES);

        //返回loginvo类型
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        //返回token loginvo
        return loginVo;
    }


    @Operation( summary = "根据请求头token查询用户信息")
    @Override
    public SysUserVo getUserInfo(String token) {
        //根据请求头的token 拼接redis的key
        //String key = "user:login:" + token;
        //String jsonString = redisTemplate.opsForValue().get(key);

       // if(StringUtils.isEmpty(jsonString)){
         //   throw new GuiguException(ResultCodeEnum.TOKEN_INVALIDATE);
        //}

        //fastjson组件可以将json字符串转成sysuser对象
        // json.toJSONString(xxx) 将java对象转成json字符串
       // SysUser sysUser = JSON.parseObject(jsonString,SysUser.class);

        //从当前线程的map获取sysUser
        SysUser sysUser = ThreadLocalUtil.getSysUser();

        //提取sysUser对象的属性 封装到Vo
        SysUserVo sysUserVo = new SysUserVo();
        sysUserVo.setId(sysUser.getId());
        sysUserVo.setName(sysUser.getName());
        sysUserVo.setAvatar(sysUser.getAvatar());

        return sysUserVo;

    }

    @Override
    public void logout(String token) {

        //删除redis中的key
        String key = "user:login:" + token;
        redisTemplate.delete(key);
    }

    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        //1.设置分页参数
        PageHelper.startPage(pageNum,pageSize);

        //2.执行sql
        List<SysUser> list = sysUserMapper.findByPage(sysUserDto);

        //3.将list集合封装成pageInfo即可
        return new PageInfo(list);
    }

    @Override
    public void addUser(SysUser sysUser) {
        //1.校验username是否重复
        String userName = sysUser.getUserName();//前端传递的username
        SysUser sysUserFromDb = sysUserMapper.findByUsername(userName);
        if(sysUserFromDb!=null){
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        //2.密码进行MD5加密
        String password = sysUser.getPassword();
        String passwordByMd5 = DigestUtils.md5Hex(password);
        sysUser.setPassword(passwordByMd5);

        //3.执行sql
        sysUserMapper.addUser(sysUser);
    }

    @Override
    public void editUser(SysUser sysUser) {
        Long id = sysUser.getId();//修改是 前端id肯定会传递数据值

        SysUser sysUserById = sysUserMapper.findById(id);

        //只有userName不一样时候,才进行逻辑判断
        if(!sysUserById.getUserName().equals(sysUser.getUserName())){
            // 因为修改和提交公用一个对话框 对话框的username进行重复试验
            // 对前端传递的用户和数据库的name进行比较 实现的功能是从数据控中 查找getUserName
            //返回值了 说明username相等
            SysUser byUsername = sysUserMapper.findByUsername(sysUser.getUserName());
            if(byUsername!=null){
                throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
            }
        }
    }

    @Override
    public void deleteById(Long id) {
        sysUserMapper.deleteById(id);
    }

    private void checkCapchaCode(LoginDto loginDto) {
        //获取的Codekey 写入redis数据库  loginDto.getCodeKey
        String codekey = loginDto.getCodeKey();
        String key = "user:code:" + codekey;
        String codeFromRedis = redisTemplate.opsForValue().get(key);

        if(codeFromRedis==null){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_expired);
        }
        //redis中的验证码和用户输入的验证码进行比较
        String capcha = loginDto.getCaptcha();
        if(!codeFromRedis.equals(capcha)){
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        redisTemplate.delete(key);
    }
}
